package com.sage.logbook.queue;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;

public class Session {
    private final String uri;
    private final byte[] postdata;
    private final byte[] responsedata;
    private byte[] processresponse;
    private final String contentType;
    private final String contentEncoding;

    public Session(String uri, byte[] postdata, byte[] responsedata, String contentType, String contentEncoding) {
        super();
        this.uri = uri;
        this.postdata = postdata;
        this.responsedata = responsedata;
        this.contentType = contentType;
        this.contentEncoding = contentEncoding;
    }

    public Session(String uri, byte[] postdata, byte[] responsedata, String contentType, String contentEncoding, boolean process) throws IOException {
        this(uri, postdata, responsedata, contentType, contentEncoding);
        if (process) {
            this.process();
        }
    }

    public void process() throws IOException {
        if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("gzip") > -1) {
            ByteArrayInputStream in = new ByteArrayInputStream(responsedata);
            ByteArrayOutputStream out = new ByteArrayOutputStream(responsedata.length << 3);

            try (GZIPInputStream gzipStream = new GZIPInputStream(in, 1 << 7)) {
                int read;
                byte[] buffer = new byte[1 << 7];

                while ((read = gzipStream.read(buffer)) != -1) {
                    out.write(buffer, 0, read);
                }

                processresponse = out.toByteArray();
            } catch (IOException e) {
                throw e;
            }
        }
    }

    public String getUri() {
        return uri;
    }

    public byte[] getPostdata() {
        return postdata;
    }

    public byte[] getResponsedata() {
        return processresponse == null ? responsedata : processresponse;
    }

    public String getContentType() {
        return contentType;
    }

    public String getContentEncoding() {
        return contentEncoding;
    }
}
